package com.longxi.tianjintianbao.ui.presenter.task_publish;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.lib.PersonnelSelector;
import com.longxi.tianjintianbao.listener.SelectDeletePersonnelListener;
import com.longxi.tianjintianbao.model.Personnel;
import com.longxi.tianjintianbao.ui.adapter.FullyGridLayoutManager;
import com.longxi.tianjintianbao.ui.adapter.GridImageAdapter;
import com.longxi.tianjintianbao.ui.adapter.multitype.AddPersonnelListViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.task_publish.ITaskPublishAtView;
import com.longxi.tianjintianbao.utils.AddPicUtils;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.luck.picture.lib.config.PictureMimeType.ofImage;

public class TaskPublishAtPresenter extends BasePresenter<ITaskPublishAtView>{

    boolean isUrgent = true;
    int degree = 1;

    public TaskPublishAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("发布任务");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                addPicUtils.selectList = PictureSelector.obtainMultipleResult(data);
                gridImageAdapter.setList(addPicUtils.selectList);
                gridImageAdapter.notifyDataSetChanged();
                break;
            case AppConst.IntentRequstCode.ACTIVITY_PERSONNEL:
                if(data != null){
                    addPerUtils.selectList = (List<Personnel>) data.getSerializableExtra(AppConst.PERSONNEL_LISTINTENT);
                    gridPersonnelAdapter.setList(addPerUtils.selectList);
                    gridPersonnelAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    /**
     * 添加任务
     */
    public void saveTask() {
        String content = getView().getEtContent().getText().toString().trim();
        String requiredate = getView().getTvRequireDate().getText().toString().trim();
        String image1 = "";
        String image2 = "";
        for (int i = 0; i < addPicUtils.selectList.size(); i++) {
            if(i == 0){
                image1 = MyUtils.imageToBase64(addPicUtils.selectList.get(i).getCompressPath());
            }else if(i == 1){
                image2 = MyUtils.imageToBase64(addPicUtils.selectList.get(i).getCompressPath());
            }
        }
        if("".equals(content) || content == null){
            MyUtils.showToast("请输入本次任务的内容");
            return;
        }
        if("".equals(requiredate) || requiredate == null){
            MyUtils.showToast("请选择要求完成时间");
            return;
        }
        if(addPerUtils.selectList.size() == 0){
            MyUtils.showToast("请选择指派的人员");
            return;
        }

        List<String> personList = new ArrayList<>();
        List<String> personidList = new ArrayList<>();

        for (int i = 0; i < addPerUtils.selectList.size(); i++) {
            if(!"".equals(addPerUtils.selectList.get(i).getUserid())){
                personList.add(addPerUtils.selectList.get(i).getUsername());
                personidList.add(addPerUtils.selectList.get(i).getUserid());
            }
        }

        mContext.showWaitingDialog(MyUtils.getResource().getString(R.string.load));

        JSONObject object = new JSONObject();
        try {
            object.put("billid", "");
            object.put("userid", MyApplication.loginUser.userid);
            object.put("assigner", personList.toString().substring(1, personList.toString().length() - 1).replace(" ", ""));
            object.put("assignerid", personidList.toString().substring(1, personidList.toString().length() - 1).replace(" ", ""));
            object.put("requiredate", requiredate);
            object.put("content", content);
            object.put("degree", degree);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveTask(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                MyUtils.showToast("发布任务成功");
                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    /**
     * 任务紧急情况
     */
    public void changeIsUrgent() {
        if(isUrgent){
            isUrgent = false;
            degree = 0;
            getView().getIvIsUrgent().setImageResource(R.mipmap.ic_select_normal);
        }else{
            isUrgent = true;
            degree = 1;
            getView().getIvIsUrgent().setImageResource(R.mipmap.ic_select_press);
        }
    }

}
